package com.example.demo.practice.mychart;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.demo.practice.R;
import com.example.demo.practice.chatview.SingleView;
import com.example.demo.practice.enterprise.Auditinfo;
import com.example.demo.practice.httpserver.HttpServer;
import com.example.demo.practice.ui.PieChartBean;
import com.example.demo.practice.ui.PieChart_View;
import com.example.demo.practice.ui.TitleView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class EtpFacilities extends AppCompatActivity {
    private HttpServer http = new HttpServer();
    private String HTTP = http.getHttp();
    private JSONArray jSONArray;
    private List<Auditinfo> mlistInfo = new ArrayList();
    private ArrayList<String> item = new ArrayList();//公司

    private ListView listView;
    private List<Integer> horList;
    private PieChart_View lv;

    private ArrayList<Integer> etp_number = new ArrayList<>();//设备总数
    private ArrayList<String> type = new ArrayList<>();//设备类型
    private ArrayList<Integer> type_number = new ArrayList<>();//类型数量
    private ArrayList<String > color = new ArrayList<>();

    int num = -1;

    private TitleView title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getSupportActionBar().hide();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.etp_facilities);
        listView = (ListView) findViewById(R.id.list);
        title = (TitleView) findViewById(R.id.title_text_tv);
        title.setText("企业设备");

        color.add("#fe996b");
        color.add("#00d4bd");
        color.add("#f868ae");
        color.add("#a65ced");
        color.add("#01c6fd");
        color.add("#c076f1");
        color.add("#00d1fc");
        color.add("#00dcfe");
        etp_number.add(0);

        lv = (PieChart_View) findViewById(R.id.pie_view);
        horList = new ArrayList<>();

        getVideoData2();
    }

    public class ListViewAdapter extends BaseAdapter {
        View[] itemViews;

        public ListViewAdapter(List<Auditinfo> mlistInfo) {
            // TODO Auto-generated constructor stub
            itemViews = new View[mlistInfo.size()];
            for(int i=0;i<mlistInfo.size();i++){
                Auditinfo getInfo=mlistInfo.get(i);    //获取第i个对象
                //调用makeItemView，实例化一个Item
                itemViews[i]=makeItemView(
                        getInfo.getText1()
                );
            }
        }

        public int getCount() {
            return itemViews.length;
        }

        public View getItem(int position) {
            return itemViews[position];
        }

        public long getItemId(int position) {
            return position;
        }

        //绘制Item的函数
        private View makeItemView(String strText1) {
            LayoutInflater inflater = (LayoutInflater) EtpFacilities.this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            // 使用View的对象itemView与R.layout.item关联
            View itemView = inflater.inflate(R.layout.etpfacilities_item, null);
            // 通过findViewById()方法实例R.layout.item内各组件
            TextView text1 = itemView.findViewById(R.id.text1);
            text1.setText(strText1);    //填入相应的值

            return itemView;
        }


        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                return itemViews[position];
            return convertView;
        }
    }

    public void setInfo(){
        mlistInfo.clear();
        int i=0;
        while(i<item.size()){
            Auditinfo information = new Auditinfo();
            information.setId(Integer.toString(i));
            information.setText1(item.get(i));

            mlistInfo.add(information); //将新的info对象加入到信息列表中
            i++;
        }
    }

    private void initHorzion(int num,int numb){
        horList.clear();
        if (numb == 0){
            for (int i=0;i<type.size();i++){
                horList.add(type_number.get(i));
            }
        }else{
            int ave = num/(type.size()-1);
            for (int i=0;i<type.size()-1;i++){
                horList.add(ave);
            }
            horList.add(num - (type.size()-1)*ave);
        }
        ArrayList<PieChartBean> lists = new ArrayList<>();
        lists.clear();

        for (int nu = 0;nu < type.size();nu ++){
            lists.add(new PieChartBean(Color.parseColor(color.get(nu)), horList.get(nu), type.get(nu)+horList.get(nu)+"个"));
        }
        lv.setData(lists);

    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            for (int i = 0; i < jSONArray.length(); i++) {
                JSONObject json = null;
                try {
                    json = (JSONObject) jSONArray.get(i);
                    String name = json.getString("name");

                    item.add(name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            jSONArray=null;

            setInfo();  //给信息赋值函数，用来测试
            listView.setAdapter(new  ListViewAdapter(mlistInfo));
            //处理Item的点击事件
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Auditinfo getObject = mlistInfo.get(position);   //通过position获取所点击的对象
                    String infoId = getObject.getId(); //获取信息id
                    num = Integer.valueOf(infoId);
                    lv.setVisibility(View.VISIBLE);
                    getVideoData();
                }
            });


            super.handleMessage(msg);
        }
    };

    private void getVideoData2() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
                    Request request = new Request.Builder()
                            .url(HTTP + "enterprise")//请求接口。如果需要传参拼接到接口后面。
                            .build();//创建Request 对象

                    Response response = client.newCall(request).execute();//得到Response 对象
                    if (response.isSuccessful()) {
                        Log.e("kwwl", "response.code()==" + response.code());
                        Log.e("kwwl", "response.message()==" + response.message());
                        //response.body().string()只可以调用一次
                        //此时的代码执行在子线程，修改UI的操作请使用handler跳转到UI线程。
                        jSONArray = new JSONArray(response.body().string());
                        handler2.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            for (int i = 0; i < jSONArray.length(); i++) {
                JSONObject json = null;
                try {
                    json = (JSONObject) jSONArray.get(i);
                    String name = json.getString("name");
                    if (item.get(num).equals("郑州信大先进技术研究院")&&name.equals(item.get(num))){
                        etp_number.set(0,etp_number.get(0) + 1);
                    }else {
                        int ind = random();
                        etp_number.add(ind);
                    }
                    int n = 0;
                    for (int j = 0;j < type.size();j++){
                        if (type.get(j).equals(name))
                        {
                            type_number.set(j,type_number.get(j) + 1);
                            n++;
                            break;
                        }
                    }
                    if (n == 0){
                        type.add(name);
                        type_number.add(1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            jSONArray=null;

            lv.setPieName(item.get(num)+etp_number.get(num)+"个");
            initHorzion(etp_number.get(num),num);


            super.handleMessage(msg);
        }
    };

    public int random(){
        Random rand = new Random();
        int ind = rand.nextInt(100);
        return ind > 4 ? ind:random();
    }//生成大于4的随机数

    private void getVideoData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象
                    Request request = new Request.Builder()
                            .url(HTTP + "getFacilities")//请求接口。如果需要传参拼接到接口后面。
                            .build();//创建Request 对象

                    Response response = client.newCall(request).execute();//得到Response 对象
                    if (response.isSuccessful()) {
                        Log.e("kwwl", "response.code()==" + response.code());
                        Log.e("kwwl", "response.message()==" + response.message());
                        //response.body().string()只可以调用一次
                        //此时的代码执行在子线程，修改UI的操作请使用handler跳转到UI线程。
                        jSONArray = new JSONArray(response.body().string());
                        handler.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
